<template>
  <div class="coach-list">
    <el-card class="coach-card">
      <template #header>
        <div class="card-header">
          <span>教练列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入教练姓名或手机号"
              style="width: 300px; margin-right: 10px"
              clearable
              @clear="handleSearch"
              @keydown.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" :loading="loading" />
              </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">添加教练</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="coachList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="email" label="邮箱" width="150" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            <span>{{ formatGender(scope.row.gender) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="specialty" label="专长" show-overflow-tooltip />
        <el-table-column prop="experience" label="经验(年)" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.status === 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑教练对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="coachFormRef"
        :model="coachForm"
        :rules="coachRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="coachForm.name" :maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="coachForm.phone" :maxlength="11" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="coachForm.email" :maxlength="100" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="coachForm.gender" placeholder="请选择性别">
            <el-option label="未知" :value="0" />
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="coachForm.birthday"
            type="date"
            placeholder="请选择生日"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="coachForm.address" type="textarea" :maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="专长" prop="specialty">
          <el-input v-model="coachForm.specialty" type="textarea" :maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="证书" prop="certificate">
          <el-input v-model="coachForm.certificate" type="textarea" :maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="经验(年)" prop="experience">
          <el-input-number
            v-model="coachForm.experience"
            :min="0"
            :max="50"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item v-if="isEdit" label="状态" prop="status">
          <el-switch
            v-model="coachForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Coach, CreateCoachRequest, UpdateCoachRequest } from '@/types/api/coach'
import { coachApi } from '@/api/modules/coach'
import { preventDuplicateSubmit } from '@/utils'
import { formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const coachList = ref<Coach[]>([])
const searchForm = reactive({
  keyword: ''
})

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const coachFormRef = ref()
const currentCoachId = ref(0)

// 表单数据
const coachForm = reactive({
  name: '',
  phone: '',
  email: '',
  gender: 0,
  birthday: '',
  address: '',
  specialty: '',
  certificate: '',
  experience: 0,
  status: 1
})

// 表单验证规则
const coachRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  experience: [
    { type: 'number', min: 0, max: 50, message: '经验应在0-50年之间', trigger: 'blur' }
  ]
}

// 格式化性别显示
const formatGender = (gender: number) => {
  switch (gender) {
    case 1: return '男'
    case 2: return '女'
    default: return '未知'
  }
}

// 获取教练列表
const getCoachList = async () => {
  loading.value = true
  try {
    const response = await coachApi.getCoachList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword
    })
    coachList.value = response.data.data.list
    pagination.total = response.data.data.total
  } catch (error) {
    ElMessage.error('获取教练列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getCoachList()
}

// 重置搜索
const handleResetSearch = () => {
  searchForm.keyword = ''
  pagination.page = 1
  getCoachList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.page = 1
  getCoachList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.page = val
  getCoachList()
}

// 添加教练
const handleAdd = () => {
  dialogTitle.value = '添加教练'
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(coachForm, {
    name: '',
    phone: '',
    email: '',
    gender: 0,
    birthday: '',
    address: '',
    specialty: '',
    certificate: '',
    experience: 0,
    status: 1
  })
}

// 编辑教练
const handleEdit = (row: Coach) => {
  dialogTitle.value = '编辑教练'
  isEdit.value = true
  dialogVisible.value = true
  currentCoachId.value = row.id
  // 填充表单数据
  Object.assign(coachForm, {
    name: row.name,
    phone: row.phone,
    email: row.email || '',
    gender: row.gender,
    birthday: row.birthday,
    address: row.address,
    specialty: row.specialty,
    certificate: row.certificate,
    experience: row.experience,
    status: row.status
  })
}

// 查看教练详情
const handleView = (row: Coach) => {
  dialogTitle.value = '教练详情'
  isEdit.value = false
  dialogVisible.value = true
  currentCoachId.value = row.id
  // 填充表单数据
  Object.assign(coachForm, {
    name: row.name,
    phone: row.phone,
    email: row.email || '',
    gender: row.gender,
    birthday: row.birthday,
    address: row.address,
    specialty: row.specialty,
    certificate: row.certificate,
    experience: row.experience,
    status: row.status
  })
}

// 删除教练
const handleDelete = (row: Coach) => {
  formUtils.handleDeleteConfirm(`教练 "${row.name}"`, async () => {
    await coachApi.deleteCoach(row.id)
    getCoachList()
  }, {
    successMessage: '删除成功',
    errorMessage: '删除失败'
  })
}

// 保存教练信息
const handleSave = async () => {
  const submitKey = isEdit.value ? `update_coach_${currentCoachId.value}` : 'create_coach'

  try {
    await preventDuplicateSubmit(submitKey, async () => {
      saveLoading.value = true
      try {
        await formUtils.handleCreateUpdate(
          isEdit.value,
          () => {
            // 添加教练
            const createData: CreateCoachRequest = {
              name: coachForm.name,
              phone: coachForm.phone,
              email: coachForm.email,
              gender: coachForm.gender,
              birthday: coachForm.birthday,
              address: coachForm.address,
              specialty: coachForm.specialty,
              certificate: coachForm.certificate,
              experience: coachForm.experience
            }
            return coachApi.createCoach(createData)
          },
          () => {
            // 编辑教练
            const updateData: UpdateCoachRequest = {
              name: coachForm.name,
              phone: coachForm.phone,
              email: coachForm.email,
              gender: coachForm.gender,
              birthday: coachForm.birthday,
              address: coachForm.address,
              specialty: coachForm.specialty,
              certificate: coachForm.certificate,
              experience: coachForm.experience,
              status: coachForm.status
            }
            return coachApi.updateCoach(currentCoachId.value, updateData)
          },
          {
            successCallback: () => {
              dialogVisible.value = false
              getCoachList()
            }
          }
        )
      } catch (error: any) {
        throw error // 重新抛出错误以确保防重复提交正确处理
      } finally {
        saveLoading.value = false
      }
    })
  } catch (error: any) {
    // 防重复提交保护捕获的错误
    if (error.message === '请勿重复提交') {
      ElMessage.warning('请勿重复提交')
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  formUtils.resetForm(coachFormRef.value, coachForm, {
    name: '',
    phone: '',
    email: '',
    gender: 0,
    birthday: '',
    address: '',
    specialty: '',
    certificate: '',
    experience: 0,
    status: 1
  })
}

// 初始化
onMounted(() => {
  getCoachList()
})
</script>

<style scoped lang="scss">
.coach-list {
  .coach-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
